import { NavBar, InfiniteScroll, Popup } from "antd-mobile"
import { useHistory, useParams } from "react-router-dom"
import classNames from "classnames"
import styles from "./index.module.scss"
import { useInitialState, useResetState } from "@/utils/use-initial-state"
import { getArticleById } from "@/store/actions/article"
import Icon from "@/components/Icon"
import CommentItem from "./components/CommentItem"
import CommentFooter from "./components/CommentFooter"
import DOMPurify from "dompurify"
import highlight from "highlight.js"
import "highlight.js/styles/github-dark.css"
import { useEffect, useState, useRef } from "react"
import { useDispatch } from "react-redux"
import { getMoreArticleComments } from "@/store/actions/article"
import dayjs from "dayjs"
// 导入本地化格式插件
import localizedFormat from "dayjs/plugin/localizedFormat"
import ContentLoader from "react-content-loader"
import { followAuthor, addArticleComment } from "@/store/actions/article"
import NoneComment from "./components/NoneComment"
import CommentInput from "./components/CommentInput"
import Reply from "./components/Reply"
import { ArtComment } from "@/types/data"
import { updateArticle } from "@/store/actions/article"
dayjs.extend(localizedFormat)

const NAV_BAR_HEIGTH = 45
// '2021-10-24 10:24:00' => '2021年10月24日'
// 创建枚举，来表示评论类型
enum CommentType {
  Article = "a",
  Comment = "c",
}
type CommentReply = {
  visible: boolean
  commentItem: ArtComment
}
const Article = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const params = useParams<{ id: string }>()
  const [loading, setLoading] = useState(true)
  const { detail } = useInitialState(() => getArticleById(params.id), "article")
  const { comment } = useInitialState(() => getMoreArticleComments(CommentType.Article, params.id, null, "replace"), "article")
  const commentRef = useRef<HTMLDivElement>(null)
  const isShowComment = useRef(false)
  const wrapperRef = useRef<HTMLDivElement>(null)
  const [commentVisible, setCommentVisible] = useState(false)
  const onCommentShow = () => setCommentVisible(true)
  const onCommentHide = () => setCommentVisible(false)

  useResetState("article") // 重置数据
  const [commentReply, setCommentReply] = useState<CommentReply>({
    visible: false,
    commentItem: {} as ArtComment,
  })

  const onCommentReplyShow = (commentItem: ArtComment) => {
    setCommentReply({
      visible: true,
      commentItem,
    })
  }

  // 关闭
  const onCommentReplyHide = () =>
    setCommentReply({
      ...commentReply,
      visible: false,
    })
  const {
    // art_id,
    aut_id,
    // // 是否点赞
    // attitude,
    // // 是否收藏
    // is_collected,
    content,
    is_followed,
    aut_name,
    aut_photo,
    comm_count,
    like_count,
    pubdate,
    read_count,
    title,
  } = detail
  const loadMoreComments = async () => {
    await dispatch(getMoreArticleComments(CommentType.Article, params.id, comment.last_id, "append"))
  }
  // 文章详情 代码内容 高亮
  useEffect(() => {
    if (detail.art_id) {
      setLoading(false)
    }
    const dgHtmlDOM = document.querySelector(".dg-html")
    const codes = dgHtmlDOM?.querySelectorAll<HTMLElement>("pre code")
    // console.log(codes)
    if (codes && codes.length > 0) {
      codes.forEach((el) => {
        // 让每个 code 内容实现代码高亮
        highlight.highlightElement(el)
      })
      return
    }

    highlight.configure({
      // 忽略警告
      ignoreUnescapedHTML: true,
    })

    // 直接找到所有的 pre 标签
    const pres = dgHtmlDOM?.querySelectorAll("pre")
    if (pres && pres.length > 0) {
      pres.forEach((el) => {
        highlight.highlightElement(el)
      })
    }
  }, [detail])

  const onFollow = () => {
    dispatch(followAuthor(aut_id, is_followed))
  }
  const onLikeOrDisLike = () => {
    dispatch(updateArticle(params.id, detail.attitude !== 1))
  }
  const onShowComment = () => {
    const wrapper = wrapperRef.current
    if (!wrapper) return
    const comment = commentRef.current
    if (!comment) return

    const commentTop = comment.getBoundingClientRect().top
    // console.log(commentTop)
    if (!isShowComment.current) {
      // 还没有展示评论信息，此时，就展示评论信息
      wrapper.scrollTo({
        // wrapper.scrollTop 表示已经滚动的距离
        top: commentTop - NAV_BAR_HEIGTH + wrapper.scrollTop,
        // 如果想要滚动时，带有动画效果，可以使用 smooth 即可
        behavior: "auto",
      })
      isShowComment.current = true
    } else {
      // 已经展示评论信息，此时，需要返回页面顶部
      wrapper.scrollTo(0, 0)
      isShowComment.current = false
    }
  }
  const renderArticle = () => {
    // 文章详情
    return (
      <div className="wrapper">
        <div className="article-wrapper">
          <div className="header">
            <h1 className="title">{title}</h1>

            <div className="info">
              <span>{dayjs(pubdate).locale("zh-cn").format("LL")}</span>
              <span>{read_count} 阅读</span>
              <span>{comm_count} 评论</span>
            </div>

            <div className="author">
              <img src={aut_photo} alt="" />
              <span className="name">{aut_name}</span>
              <span onClick={onFollow} className={classNames("follow", is_followed ? "followed" : "")}>
                {is_followed ? "已关注" : "关注"}
              </span>
            </div>
          </div>

          <div className="content">
            <div
              className="content-html dg-html"
              dangerouslySetInnerHTML={{
                __html: DOMPurify.sanitize(content),
              }}
            />
            ;<div className="date">发布文章时间：{dayjs(pubdate).locale("zh-cn").format("LL")}</div>
          </div>
        </div>

        <div className="comment" ref={commentRef}>
          <div className="comment-header">
            <span>全部评论（{comm_count}）</span>
            <span>{like_count} 点赞</span>
          </div>
          {comm_count === 0 ? (
            <NoneComment />
          ) : (
            <div className="comment-list">
              {comment.results.map((item) => {
                return <CommentItem key={item.com_id} {...item} />
              })}
              <InfiniteScroll hasMore={comment.end_id !== comment.last_id} loadMore={loadMoreComments} />
            </div>
          )}
          {/* <div className="comment-list">
            <CommentItem />
          </div> */}
        </div>
      </div>
    )
  }
  const onAddComment = async (content: string) => {
    await dispatch(addArticleComment(detail.art_id, content))
    // 关闭评论抽屉
    onCommentHide()
  }
  const renderReply = () => {
    return (
      <Popup className="reply-popup" position="right" visible={commentReply.visible}>
        <div className="comment-popup-wrapper">
          <Reply commentItem={commentReply.commentItem} onClose={onCommentReplyHide} />
        </div>
      </Popup>
    )
  }
  if (loading) {
    return (
      // 根据当前页面结构，设计好的 loading 效果
      <ContentLoader speed={2} width={375} height={230} viewBox="0 0 375 230" backgroundColor="#f3f3f3" foregroundColor="#ecebeb">
        <rect x="16" y="8" rx="3" ry="3" width="340" height="10" />
        <rect x="16" y="26" rx="0" ry="0" width="70" height="6" />
        <rect x="96" y="26" rx="0" ry="0" width="50" height="6" />
        <rect x="156" y="26" rx="0" ry="0" width="50" height="6" />
        <circle cx="33" cy="69" r="17" />
        <rect x="60" y="65" rx="0" ry="0" width="45" height="6" />
        <rect x="304" y="65" rx="0" ry="0" width="52" height="6" />
        <rect x="16" y="114" rx="0" ry="0" width="340" height="15" />
        <rect x="263" y="208" rx="0" ry="0" width="94" height="19" />
        <rect x="16" y="141" rx="0" ry="0" width="340" height="15" />
        <rect x="16" y="166" rx="0" ry="0" width="340" height="15" />
      </ContentLoader>
    )
  }

  const renderCommentPopup = () => {
    return (
      <Popup destroyOnClose className="comment-popup" position="bottom" visible={commentVisible} onMaskClick={onCommentHide}>
        <div className="comment-popup-wrapper">
          <CommentInput onAddComment={onAddComment} onClose={onCommentHide} />
        </div>
      </Popup>
    )
  }
  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar
          onBack={() => history.go(-1)}
          right={
            <span>
              <Icon type="icongengduo" />
            </span>
          }
        >
          <div className="nav-author">
            <img src="http://geek.itheima.net/images/user_head.jpg" alt="" />
            <span className="name">{aut_name}</span>
            <span onClick={onFollow} className={classNames("follow", is_followed ? "followed" : "")}>
              {is_followed ? "已关注" : "关注"}
            </span>
          </div>
        </NavBar>
        {/* 文章详情和评论 */}
        {renderArticle()}

        {/* 底部评论栏 */}
        <CommentFooter onLikeOrDisLike={onLikeOrDisLike} onCommentPopup={onCommentShow} onShowComment={onShowComment} {...detail} />
        {renderCommentPopup()}
        {renderReply()}
      </div>
    </div>
  )
}

export default Article
